<script>
let { chunk, flatten } = require("lodash");
export default {
  props: {
    showTitle: {
      type: Boolean,
      default: true,
    },
    showDescription: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: "",
    },
    description: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      resizeObserver: null,
      wrapWidth: 1200,
    };
  },
  mounted() {
    this.resizeObserver = new ResizeObserver(this.resizeHandler);
    this.resizeObserver.observe(this.$refs.wrap);
    this.resizeHandler();
  },
  beforeDestroy() {
    this.resizeObserver.unobserve(this.$refs.wrap);
    this.resizeObserver = undefined;
  },
  methods: {
    resizeHandler() {
      if (this.$refs.wrap) {
        this.wrapWidth = this.$refs.wrap.getBoundingClientRect().width;
      }
    },
  },
  render(h) {
    let nodes = [...this.$slots.default];
    const lastNode = nodes[nodes.length - 1];
    const minWidth = lastNode.data.props.fieldStyle.minWidth;
    const itemWidth = (this.wrapWidth - Number(minWidth.slice(0, -2))) / 3;

    nodes.slice(0, -1).forEach((node) => {
      if (node.componentInstance && node.componentInstance.$el) {
        if (
          this.wrapWidth / 4 <= Number(minWidth.slice(0, -2)) ||
          nodes.length < 4
        ) {
          node.componentInstance.$el.style.width = itemWidth + "px";
          node.componentInstance.$el.style.flex = `0 0 ${itemWidth + "px"}`;
        } else {
          node.componentInstance.$el.style = null;
        }
      }
      if (
        this.wrapWidth / 4 <= Number(minWidth.slice(0, -2)) ||
        nodes.length < 4
      ) {
        node.data.style = {
          width: itemWidth + "px",
          flex: `0 0 ${itemWidth + "px"}`,
        };
      }
    });
    if (this.$slots.default.length % 4 !== 0) {
      const len = 4 - (this.$slots.default.length % 4);
      for (let i = 0; i < len; i++) {
        const emtpyNode = h("div", {
          class: { "gen-form-item": true },
        });
        nodes.push(emtpyNode);
      }
    }

    const groups = chunk(nodes, 4);
    nodes = flatten(
      groups.map((group) => {
        return [
          ...group,
          h("div", { class: "divider", style: "width: 100%; float: left;" }),
        ];
      })
    );

    return h("div", { ref: "wrap", class: "field-group-wrap" }, [
      h("h3", { class: "field-group-wrap__title" }, this.title),
      h("div", { class: "field-group-wrap__box" }, nodes),
    ]);
  },
};
</script>
